<?php
class Jqueryplugins extends Model_Abstract
{
	public $tableName = 'jqueryplugins';
	
	public $descriptionVars = array(
		'[[a_rf]]' => '当前编辑插件生成的附件目录 ',
		'<*' => '&lt;',
		'*>' => '&gt;'
	);
	
	public function descriptionVarsTrans($attributes = null)
	{
		$attributes = $attributes? $attributes : $this->attributes;
		return array(
			'[[a_rf]]' => FRONTEND_JQROOT . $attributes['root_foldername'] .'/',
			'<*' => '&lt;',
			'*>' => '&gt;'
		);
	}
	
	protected $_validation = array(
		'name' => array(
			array('max_length', '模板名称长度不能超过100', 100),
			array('not_empty', '请填写模板名称')
		),
		'root_foldername' => array(
			array('max_length', '资源路径最长100个字符', 100),
		),
		'sketch' => array(
			array('max_length', '请在500个字以内描述模板', 500),
		),
		'description' => array(
			array('max_length', '请在99999999个字以内描述模板', 99999999),
		),
		'thumbnail' => array(
			array('max_length', '预览图名称最长50个字符', 50),
			array('not_empty', '请放置一张预览图')
		),
		'download_pack' => array(
			array('max_length', '下载包文件名最长50个字符', 50),
		),
		'view_num' => array(
			array('is_int', 'view_num必须是数字'),
		),
	);
	
	public function init()
	{
		$this->initAttributes();
		$this->_notFilterScriptTagsAttributes = array('description');
	}
	
	public static function model($classname = __CLASS__)
	{
		return parent::model($classname);
	}
	
	public function attributeLabels()
	{
	}

	public function mergeTypeWithId($types, $jqueryplugins)
	{
		foreach($jqueryplugins as $k => $jq){
			$jqueryplugins[$k]['type_name'] = '';
			$jqueryplugins[$k]['type_name_en'] = '';
	
			if(!empty($types[$jq['type_id']])){
				$jqueryplugins[$k]['type_name'] = $types[$jq['type_id']]['name'];
				$jqueryplugins[$k]['type_name_en'] = $types[$jq['type_id']]['name_en'];
			}
		}
		return $jqueryplugins;
	}
	
	public function getAll()
	{
		$types = Types::model()->find('*', array('tablename' => 'jqueryplugins'), array('setResultKey' => 'id'));
		$jqueryplugins = $this->find('*');
		
		return $this->mergeTypeWithId($types, $jqueryplugins);
	}
	
	
	public function paginationGetAll($page, $type_id)
	{
		$types = Types::model()->find('*', array('tablename' => 'jqueryplugins'), array('setResultKey' => 'id'));
		
		$perPage = JQUERYPLUGINS_LIST_PERPAGE;
		$limit = " LIMIT " .($page-1)*$perPage . ", {$perPage}";
		
		$sqlWhere = '';
		$query = array();
		$vars = array();
		if(!empty($type_id)){
			$query[] = ' type_id = ? ';
			$vars[] = $type_id;
		}
		if(!empty($query)){
			$sqlWhere = ' WHERE ' . implode(' AND ', $query);
		}
		
		$sqlCount = " SELECT COUNT(*) total_num FROM jqueryplugins " . $sqlWhere;
		$result = $this->_connection->query($sqlCount, $vars);
		if(!empty($result)){
			$totalCount = $result[0]['total_num'];
		}else{
			$totalCount = 0;
		}
		
		$sql = " SELECT jq.* FROM jqueryplugins jq ";
		
		$sql .= $sqlWhere . $limit;
		$result = $this->_connection->query($sql, $vars);
		$result = $this->mergeTypeWithId($types, $result);
		if(!empty($result)){
			foreach($result as $k => $r){
				$result[$k] = $this->replaceDescriptionVars($r);
			}
		}
		
		$result['totalCount'] = $totalCount;
		return $result;
	}
	
	public function initAttributes()
	{
		$this->attributes = array(
			'name' => '',
			'sketch' => '',
			'description' =>'',
			'root_foldername' => '',
			'thumbnail' => '',
			'download_pack' => '',
			'view_num' => '',
			'download_num' => '',
			'type_id' => '',
			'recommend' => '',
			'created_date' => '',
			'created_int' => ''
		);
	}
	
	public function replaceSelfDescriptionVars()
	{
		if(!empty($this->attributes['description'])){
			foreach($this->descriptionVarsTrans() as $from => $to){
				$this->attributes['description'] = str_replace($from, $to, $this->attributes['description']);
			}
		}	
	}
	
	public function replaceDescriptionVars($attributes)
	{
		if(!empty($attributes['description'])){
			foreach($this->descriptionVarsTrans($attributes) as $from => $to){
				$attributes['description'] = str_replace($from, $to, $attributes['description']);
			}
		}
		
		return $attributes;
	}
	
	/**
	 * 
	 * htmlspecialchars in pre tags
	 * @param array $content
	 */
	public function replacePreContent($attributes)
	{
		if(!empty($attributes['description'])){
			phpQuery::newDocument($attributes['description']);
			foreach(pq('pre') as $pre){
				$afterSpecialchars = htmlspecialchars(pq($pre)->html());
				pq($pre)->html($afterSpecialchars);
			}
			
			$d = phpQuery::getDocument();
			$attributes['description'] = $d->html();
			phpQuery::$documents = array();			
		}
		return $attributes;
	}
	
	protected function _find($fields = '*', $attributes = array(), $constraint = array(), $conditions = array(), $params = array())
	{
		$result = parent::_find($fields, $attributes, $constraint, $conditions, $params);
		$c = array_merge(
			$this->_constraintFind,
			array('replaceDescriptionVars' => false, 'htmlSpecialcharsPreContent' => false, 'mergeType' => false),
			$constraint
		);
		extract($c);
		
		if($replaceDescriptionVars){
			if($onlyOne){
				$result = $this->replaceDescriptionVars($result);
			}else{
				foreach($result as $k => $r){
					$result[$k] = $this->replaceDescriptionVars($r);
				}
			}
		}
		if($htmlSpecialcharsPreContent){
			if($onlyOne){
				$result = $this->replacePreContent($result);
			}else{
				foreach($result as $k => $r){
					$result[$k] = $this->replacePreContent($r);
				}
			}
		}
		
		if($mergeType){
			$types = Types::model()->find('*', array('tablename' => 'jqueryplugins'), array('setResultKey' => 'id'));
			$result = $this->mergeTypeWithId($types, $result);
		}
		
		return $result;
	}
	
	protected function _save($validate = true)
	{
		if(!empty($this->attributes[$this->primaryKey])){
			$oldData = $this->_find('*', array('id' => $this->attributes['id']), array('onlyOne' => true));
			
			if($oldData['name'] != $this->attributes['name']){
				if($this->count(array('name' => $this->attributes['name'])) > 0){
					$this->_validationError['name'][] = 'name' . '已存在';
					return false;
				}
			}
			if($oldData['root_foldername'] != $this->attributes['root_foldername']){
				if($this->count(array('root_foldername' => $this->attributes['root_foldername'])) > 0){
					$this->_validationError['root_foldername'][] = 'root_foldername' . '已存在';
					return false;
				}
				
				rename(
					JQUERYPLUGINS_DIR . '/' . $oldData['root_foldername'],
					JQUERYPLUGINS_DIR . '/' . $this->attributes['root_foldername']
				);
			}
		}
		
		$this->_before_sql();
		return parent::_save($validate);
	}

	public function saveFiles($fileInfos)
	{
		$root = JQUERYPLUGINS_DIR . '/' . $this->attributes['root_foldername'];
		@mkdir($root, 0777, true);
		
		if(!empty($fileInfos['name']['attachment'])){
			$attachments = $fileInfos['name']['attachment'];
			$tmpName = $fileInfos['tmp_name']['attachment'];
			if(!is_array($attachments)){
				$attachments = array($attachments);
			}
			if(!is_array($tmpName)){
				$tmpName = array($tmpName);
			}
			
			foreach($attachments as $k => $attach){
				if(!empty($attach)){
					copy($tmpName[$k], $root . '/' . $attach);
				}
			}
		}
		
		if(!empty($fileInfos['name']['thumbnail'])){
			$thumbnail = $this->attributes['thumbnail'];
			$tmpName = $fileInfos['tmp_name']['thumbnail'];
			
			copy($tmpName, $root . '/' . $thumbnail);
		}
		
		if(!empty($fileInfos['name']['download_pack'])){
			$download_pack = $this->attributes['download_pack'];
			$tmpName = $fileInfos['tmp_name']['download_pack'];
			
			copy($tmpName, $root . '/' . $download_pack);
		}
		
		return true;
	}
	
	protected function _delete($deleteFiles = false, $attributes = array(), $conditions = array(), $params = array())
	{
		if($deleteFiles){
			$root = $this->find('root_foldername', $attributes, array('onlyOne' => true, 'stripName' => true), $conditions, $params);
			$root = JQUERYPLUGINS_DIR . '/' . $root;
			@mkdir($root, 0777, true);
			Util::removePath($root);
		}
		$this->_before_sql();
		return parent::_delete($attributes, $conditions, $params);
	}
	

	public function getDefaultshows($num = JQUERYPLUGINS_DEFAULT_SHOWNUM)
	{
		$constraint = array(
			'orderBy' => array(
				'fields' => array('view_num', 'download_num'),
				'seq' => array('DESC', 'DESC')
			),
			'limit' => $num
		);
	
		$types = Types::model()->find('*', array('tablename' => 'jqueryplugins'), array('setResultKey' => 'id'));
		$jqueryPlugins = $this->find('*', null, $constraint);
	
		return $this->mergeTypeWithId($types, $jqueryPlugins);
	}
	
	public function getRecommends()
    {
    	$recommends = $this->find('*', array('recommend'=> '1'));
    	return $recommends;
    }
    
	public function getTopViews($num = JQUERYPLUGINS_TOPVIEWS_SHOWNUM)
    {
    	$vieweds = $this->find('*', null, array('orderBy'=> array('fields' => 'view_num', 'seq' => 'DESC'), 'limit' => $num));
    	return $vieweds;
    }
    
    public function getTopDownloads($num = JQUERYPLUGINS_TOPDOWNLOADS_SHOWNUM)
    {
    	$downloads = $this->find('*', null, array('orderBy'=> array('fields' => 'download_num', 'seq' => 'DESC'), 'limit' => $num));
    	return $downloads;
    }
	
}